﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace ReguLiteCM
{
	public partial class MainWindow : Form
	{
		public MainWindow()
		{
			InitializeComponent();
		}

		private void DoMatch_Click(object sender, System.EventArgs e)
		{
			if (string.IsNullOrWhiteSpace(ExpressionInput.Text))
			{
				MessageBox.Show("Please enter an expression", "Expression missing", MessageBoxButtons.OK, MessageBoxIcon.Warning);
			}
			else
			{
				string inputText = TestInput.Text;

				if (string.IsNullOrWhiteSpace(inputText))
				{
					MessageBox.Show("Please enter some test input", "Test input missing", MessageBoxButtons.OK, MessageBoxIcon.Warning);
				}
				else
				{
					CheckForMatches();
				}
			}
		}

		/// <summary>
		/// 
		/// </summary>
		private void CheckForMatches()
		{
			try
			{
				IRegexStrategy strategy = SelectedLanguageStrategy;
				strategy.Global = ModGlobal.Checked;
				strategy.IgnoreCase = ModIgnoreCase.Checked;
				strategy.MultiLine = ModMultiline.Checked;

				IEnumerable<string> matches = strategy.FindMatches();

				ResultOutput.Nodes.Clear();

				if (matches != null && matches.Count() > 0)
				{
					foreach (string match in matches)
					{
						// TODO: are empty strings valid array elements?
						ResultOutput.Nodes.Add(string.Concat("[", match, "]"));
					}
				}
				else
				{
					TreeNode node = new TreeNode("* NO MATCHES FOUND *") {ForeColor = Color.Red};
					ResultOutput.Nodes.Add(node);
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.ToString(), "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// 
		/// </summary>
		private IRegexStrategy SelectedLanguageStrategy
		{
			get
			{
				string inputText = TestInput.Text;
				string expressionText = ExpressionInput.Text;

				if (LanguageDotNet.Checked)
				{
					return new DotNetRegexStrategy(expressionText, inputText);
				}
				if (LanguageJavascript.Checked)
				{
					return new JavascriptRegexStrategy(expressionText, inputText);
				}
				if (LanguagePerl.Checked)
				{
					return new PerlRegexStrategy(expressionText, inputText);
				}

				throw new InvalidOperationException("Unrecognized language.");
			}
		}
	}
}
